import { fromError } from 'zod-validation-error'
import { eq } from 'drizzle-orm'
import { updateRoleSchema, rolesTable } from '~~/server/db/schema/role'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))

  if (!id || isNaN(id)) {
    throw createError({
      statusCode: 400,
      message: '角色ID格式错误'
    })
  }

  const validationResult = await readValidatedBody(event, (body) =>
    updateRoleSchema.safeParse(body)
  )

  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }

  const updateData = validationResult.data

  try {
    // 检查角色是否存在
    const [existingRole] = await db.select().from(rolesTable).where(eq(rolesTable.id, id)).limit(1)

    if (!existingRole) {
      throw createError({
        statusCode: 404,
        message: '角色不存在'
      })
    }

    // 更新角色
    await db.update(rolesTable).set(updateData).where(eq(rolesTable.id, id))
    setResponseStatus(event, 200)
    return {
      message: '角色更新成功',
      data: {
        id: rolesTable.id
      }
    }
  } catch (error: any) {
    console.error('Update Role error:', error)
    throw createError({
      statusCode: 500,
      message: '更新角色失败'
    })
  }
})
